<?php

namespace Biz\service\wikiRanking;


use Biz\cache\category\UserRealTimeCategory;
use Biz\cache\wiki\UserRecommendWikiRanking;
use Biz\cache\wiki\WikiRanking as cacheWikiRanking;
use Biz\model\brand\Brand as mBrand;
use Biz\model\wiki\WikiRankingBrand;
use Biz\model\wiki\WikiRankingBrandData;
use Biz\model\wiki\WikiRankingCategory;
use Biz\model\wiki\WikiRankingConfig;
use Biz\model\wiki\WikiRankingData;
use Biz\model\wiki\WikiRankingHot;
use Biz\model\wiki\WikiRankingPublicPraise;
use Biz\pockets\serviceTrait\_Async;
use Biz\service\brand\Brand;
use Biz\service\wiki\Wiki;
use Biz\service\wiki\Wiki as sWiki;
use Biz\service\wiki\WikiBasic;
use Doraemon\cache\UserCounter;
use Doraemon\service\Format\Blank\HandleBlank;
use Doraemon\service\Format\Note\HandleNote;
use Doraemon\service\statSign\Basic as statSign;
use Doraemon\service\User as sUser;
use Doraemon\service\UserPortrait\UserPortraitApi;
use Doraemon\tools\BlockType;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\LinkFormat;
use Doraemon\tools\Log;
use hhz\constant\redis\redisKeys;
use Hhz\Redis\newCache;


/**
 * 榜单
 * Class Ranking
 * @package Biz\service\wikiRanking
 */
class Ranking
{
    use _Async;

    const CONST_RANKING_WEEK_DAY = 3;//榜单日期为每周三

    const TOP_SHOW_CNT = 5;//分类榜单最小展示数

    const TYPE_HOT = 1;//热榜
    const TYPE_PUBLIC_PRAISE = 2;//口碑榜
    const TYPE_BRAND = 3;//品牌榜

    const TYPE_PUBLIC_UP = 5;//住友口碑榜
    const TYPE_HOT_UP = 4;//热度飙升榜

    const BRAND_URL = '/brand/bangdan/brand-ranking';


    public static function getListByRankingIds($rankingIds, $pageSize = 20)
    {
        if (empty($rankingIds)) {
            return [];
        }
        list($cateData, $noCacheKeys) = cacheWikiRanking::getWikiRankingList($rankingIds);
        if ($noCacheKeys) {
            $rankingList = self::getRankingList($noCacheKeys);
            $expireTime = self::getMaxRankingExpireTime();
            cacheWikiRanking::setWikiRankingList($rankingList, $expireTime);
            $list = $cateData + $rankingList;
        } else {
            $list = $cateData;
        }
        $list = array_slice($list, 0, $pageSize);
        return array_values($list);
    }

    private static function getRankingList($rankingIds)
    {
        $day = self::getRankingDay();
        $rankingDataList = cacheWikiRanking::getWikiRankingDataIds($day);
        $rankingDataIds = $rankingDataList ? array_keys($rankingDataList) : [];

        $hotRankingIds = self::getAllShowRankingIds(self::TYPE_HOT);
        $hotTopRankingIds = array_intersect($rankingDataIds, $hotRankingIds);

        $rankingIds = $rankingIds ? array_intersect($rankingIds, $hotTopRankingIds) : $hotTopRankingIds;

        $hotRankingList = $rankingIds ? WikiRankingHot::selectByWhere([
            'ranking_id' => $rankingIds,
            'ranking_day' => $day,
            'ranking_state' => WikiRankingHot::RANKING_STATE_SHOW,
            'ORDER' => ['top_num' => 'ASC', 'score' => 'DESC'],
        ]) : [];
        $hotRankingBasicIds = [];
        $basicIds = [];
        $brandIds = [];
        $basicPicInfo = [];
        $hotRankings = [];
        foreach ($hotRankingList as $row) {
            $basicIds[] = $row['basic_id'];
            $hotRankingBasicIds[$row['ranking_id']][] = $row['basic_id'];
            $brandIds[$row['basic_id']] = $row['brand_id'];
            //basic pic id
            if ($row['basic_pic_id']) {
                $basicPicInfo[$row['basic_id']] = $row['basic_pic_id'];;
            }
            //basic pic id
            $hotRankings[$row['ranking_id']] = $row;
        }
        $wikiBasicList = $basicIds ? Wiki::getWikiBaseListByBasicIds($basicIds) : [];
        $wikiBasicList = self::HandleBasicPic($wikiBasicList, $basicPicInfo);

        $brandList = $brandIds ? Brand::getBrandListByIds4App(array_values($brandIds)) : [];

        $list = [];
        foreach ($rankingIds as $rankingId) {
            $hotRanking = $hotRankings[$rankingId];
            $rankingInfo = [
                'ranking_id' => $rankingId,
                'ranking_name' => $hotRanking['ranking_name'],
                'user_count' => $rankingDataList[$rankingId],
                'ranking_list' => [],
                'wiki_count' => 0,
            ];
            $rankingList = [];
            if (isset($hotRankingBasicIds[$rankingId])) {
                $i = 0;
                foreach ($hotRankingBasicIds[$rankingId] as $basicId) {
                    if (isset($wikiBasicList[$basicId])) {
                        $wikiInfo = $wikiBasicList[$basicId];
                        $brandInfo = $brandList[$brandIds[$basicId]] ?? [];
                        if ($wikiInfo['id']) {
                            if ($i < 3) {
                                $rankingList[] = [
                                    'basic_id' => $wikiInfo['basic_id'],
                                    'wiki_id' => $wikiInfo['id'],
                                    'title' => $wikiInfo['title'],
                                    'top' => $i + 1,
                                    'cover_img' => isset($wikiInfo['cover_img']) ? $wikiInfo['cover_img'] : '',
                                    'brand_name' => $brandInfo['name'] ?? '',
                                    'actual_min_price' => $wikiInfo['actual_min_price'],
                                    'actual_max_price' => $wikiInfo['actual_max_price'],
                                ];
                            }
                            $i++;
                        }
                    }
                }
            }
            $rankingInfo['wiki_count'] = $i;
            if ($rankingList) {
                $rankingInfo['ranking_list'] = $rankingList;
                $list[$rankingId] = $rankingInfo;
            }
        }
        return $list;
    }


    /**
     * @param $rankingIds
     * @param int $pageSize
     * @return array
     */
    private static function getBrandListByRankingIds($rankingIds, $pageSize = 20, $brand_count = 10)
    {
        $day = self::getRankingDay();
        $rankingDataList = cacheWikiRanking::getWikiRankingDataIds($day);
        $rankingDataIds = $rankingDataList ? array_keys($rankingDataList) : [];

        $brandRankingIds = self::getAllShowRankingIds(self::TYPE_BRAND);
        $brandTopRankingIds = array_intersect($rankingDataIds, $brandRankingIds);

        $rankingIds = $rankingIds ? array_intersect($rankingIds, $brandTopRankingIds) : $brandTopRankingIds;

        $brandRankingList = $rankingIds ? WikiRankingBrand::selectByWhere([
            'ranking_id' => $rankingIds,
            'ranking_day' => $day,
            'ranking_state' => WikiRankingBrand::RANKING_STATE_SHOW,
            'ORDER' => ['top_num' => 'ASC', 'score' => 'DESC'],
        ]) : [];

        $brandRankingBrandIds = [];
        $brandIds = [];
        $brandRankings = [];
        foreach ($brandRankingList as $row) {
            $brandIds[] = $row['brand_id'];
            $brandRankingBrandIds[$row['ranking_id']][] = $row['brand_id'];
            $brandRankings[$row['ranking_id']] = $row;
        }
        $brandList = $brandIds ? Brand::getBrandListByIds4App($brandIds) : [];
        $list = [];
        foreach ($rankingIds as $rankingId) {
            $brandRanking = $brandRankings[$rankingId];
            $rankingInfo = [
                'ranking_id' => $rankingId,
                'ranking_name' => $brandRanking['ranking_name'],
                'user_count' => $rankingDataList[$rankingId],
                'ranking_list' => [],
                'brand_count' => 0,
            ];
            $rankingList = [];
            if (isset($brandRankingBrandIds[$rankingId])) {
                $i = 0;
                foreach ($brandRankingBrandIds[$rankingId] as $brandId) {
                    if (isset($brandList[$brandId])) {
                        $brandInfo = $brandList[$brandId];
                        if ($i < $brand_count) {
                            $rankingList[] = [
                                'brand_id' => $brandId,
                                'brand_name' => $brandInfo['name'],
                                'top' => $i + 1,
                                'logo' => isset($brandInfo['logo']) ? $brandInfo['logo'] : '',
                            ];
                        }

                        $i++;
                    }
                }
            }
            $rankingInfo['brand_count'] = $i;
            if ($rankingList) {
                $rankingInfo['ranking_list'] = $rankingList;
                $list[] = $rankingInfo;
            }
        }
        $list = array_slice($list, 0, $pageSize);

        return $list;
    }


    public static function getHeadInfo($ranking_id, $type)
    {
        $result = [];
        $configInfo = WikiRankingConfig::getByWhere([
            'id' => $ranking_id,
            'config_state' => WikiRankingConfig::STATUS_NORMAL,
        ]);
        if (empty($configInfo)) {
            return $result;
        }
        $counter = self::getCounterByRankingId($ranking_id);

        $result = [
            'pid' => $configInfo['pid'],
            'ranking_id' => $ranking_id,
            'ranking_name' => $configInfo['ranking_name'],
            'update_time' => '榜单每周三零点更新',
            'is_hot' => $counter['hot'] >= self::TOP_SHOW_CNT ? 1 : 0,
            'is_brand' => $counter['brand'] >= self::TOP_SHOW_CNT ? 1 : 0,
            'is_userlike' => $counter['usr_like'] >= self::TOP_SHOW_CNT ? 1 : 0,
        ];
        $counter = self::getCounterByRankingId($ranking_id);

        if ($counter && is_array($counter)) {
            $wikiCnt = $counter['wiki'] + $counter['content'];
            if ($wikiCnt > 10000) {
                $wikiCnt = sprintf("%.1f", $wikiCnt / 10000) . 'W';
            }
            if ($wikiCnt > 0) {
                $result['desc'] = "本榜单由 " . $counter['usr'] . " 位住友从 " . $wikiCnt . " 个好物中选出";
            }
            if ($type == self::TYPE_BRAND && $counter['brand_cnt'] > 0) {
                $result['desc'] = '本榜单由 ' . $counter['usr'] . ' 位住友从 ' . $counter['brand_cnt'] . ' 个品牌中选择';

            }

        }

        return $result;
    }

    public static function getCounterByRankingId($ranking_id)
    {
        $rankingDay = self::getRankingDay();
        $counter = [];
        $rankData = WikiRankingData::getByWhere(['ranking_id' => $ranking_id, 'ranking_day' => $rankingDay]);
        $counter['usr'] = (int)$rankData['rank_cnt'] ?: 0;
        if ($counter['usr'] > 10000) {
            $counter['usr'] = sprintf("%.1f", $counter['usr'] / 10000) . 'W';
        }
        $counter['wiki'] = (int)$rankData['wiki_cnt'] ?: 0;
        $counter['content'] = (int)$rankData['content_cnt'] ?: 0;
        $counter['brand_cnt'] = (int)$rankData['brand_cnt'] ?: 0;
        if ($counter['brand_cnt'] > 10000) {
            $counter['brand_cnt'] = sprintf("%.1f", $counter['brand_cnt'] / 10000) . 'W';
        }

        $counter['hot'] = (int)WikiRankingHot::selectCountWhere([
            'ranking_id' => $ranking_id,
            'ranking_day' => $rankingDay,
            'ranking_state' => WikiRankingHot::RANKING_STATE_SHOW,
        ]) ?: 0;
        $counter['brand'] = (int)WikiRankingBrand::selectCountWhere([
            'ranking_id' => $ranking_id,
            'ranking_day' => $rankingDay,
            'ranking_state' => WikiRankingBrand::RANKING_STATE_SHOW,
        ]) ?: 0;
        $counter['usr_like'] = (int)WikiRankingPublicPraise::selectCountWhere([
            'ranking_id' => $ranking_id,
            'ranking_day' => $rankingDay,
            'ranking_state' => WikiRankingPublicPraise::RANKING_STATE_SHOW,
        ]) ?: 0;

        return $counter;
    }


    public static function getHotByRankingId($ranking_id, $active_uid = 0, $limit = 20)
    {
        $rankingDay = self::getRankingDay();
        $list = WikiRankingHot::getShowTop($ranking_id, $rankingDay, $limit);
        if (count($list) <= self::TOP_SHOW_CNT) {
            //    return [];
        }
        $basic_ids = [];
        $basicPicHash = [];
        foreach ($list as $val) {
            $basic_ids[] = $val['basic_id'];
            if ($val['basic_pic_id']) {
                $basicPicHash[$val['basic_id']] = $val['basic_pic_id'];
            }
        }

        $basic_info = $basic_ids ? sWiki::getWikiListByBasicIdsForRanking($basic_ids, $active_uid) : [];
        $basic_info = self::HandleBasicPic($basic_info, $basicPicHash);
        $result = [];

        if ($list && is_array($list)) {
            $i = 0;
            foreach ($list as $val) {
                if ($val['basic_id'] && $basic_info[$val['basic_id']]) {
                    $basic_info[$val['basic_id']]['score'] = round($val['score'], 1);
                    $statSign = statSign::genStatSign(statSign::MODULE_BANGDAN_DETAIL_LIST, [
                        statSign::EXTEND_KEY_OBJ_ID => $basic_info[$val['basic_id']]['id'],
                        statSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI,
                        statSign::EXTEND_KEY_OBJ_UID => $basic_info[$val['basic_id']]['brand_id'],
                        statSign::EXTEND_KEY_INDEX => $i,
                        statSign::EXTEND_KEY_POS => 'location_1',
                        statSign::EXTEND_KEY_RELATE_OBJ_ID => $ranking_id,
                        statSign::EXTEND_KEY_RELATE_OBJ_TYPE => BlockType::TYPE_RANKING,
                    ], [
                        'tab' => 'hot'
                    ]);
                    $basic_info[$val['basic_id']]['statSign'] = $statSign;
                    $result[] = $basic_info[$val['basic_id']];
                    $i++;
                }
            }
        }

        return $result;
    }

    public static function getUserLikeByRankingId($ranking_id, $active_uid = 0, $limit = 20)
    {
        $rankingDay = self::getRankingDay();

        $list = WikiRankingPublicPraise::getShowTop($ranking_id, $rankingDay, $limit);

        if (count($list) <= self::TOP_SHOW_CNT) {
            //  return [];
        }
        $basic_ids = [];
        $basicPicHash = [];
        foreach ($list as $val) {
            $basic_ids[] = $val['basic_id'];
            if ($val['basic_pic_id']) {
                $basicPicHash[$val['basic_id']] = $val['basic_pic_id'];
            }
        }
        $basic_info = $basic_ids ? sWiki::getWikiListByBasicIds($basic_ids, $active_uid) : [];
        $basic_info = self::HandleBasicPic($basic_info, $basicPicHash);


        $obj_ids = array_column($list, 'obj_id') ?: [];
        $content_info = [];
        if ($obj_ids && is_array($obj_ids)) {
            $content_info = self::getContentInfo($obj_ids);
        }
        $result = [];
        if ($list && is_array($list)) {
            $i = 0;
            foreach ($list as $val) {
                if ($val['basic_id'] && $basic_info[$val['basic_id']] && $val['obj_id'] && $content_info[$val['obj_id']]) {
                    $basic_info[$val['basic_id']]['score'] = round($val['score'], 1);
                    $wikiInfo = $basic_info[$val['basic_id']];
                    $wikiInfo['statSign'] = statSign::genStatSign(statSign::MODULE_BANGDAN_DETAIL_LIST, [
                        statSign::EXTEND_KEY_OBJ_ID => $basic_info[$val['basic_id']]['id'],
                        statSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI,
                        statSign::EXTEND_KEY_OBJ_UID => $basic_info[$val['basic_id']]['brand_id'],
                        statSign::EXTEND_KEY_INDEX => $i,
                        statSign::EXTEND_KEY_POS => 'location_3',
                        statSign::EXTEND_KEY_RELATE_OBJ_ID => $ranking_id,
                        statSign::EXTEND_KEY_RELATE_OBJ_TYPE => BlockType::TYPE_RANKING,
                        statSign::EXTEND_KEY_URL_TYPE => BlockType::TYPE_WIKI,
                    ], [
                        'tab' => 'publicpraise'
                    ]);
                    $contentInfo = $content_info[$val['obj_id']];

                    switch ($contentInfo['type']) {
                        case BlockType::TYPE_PHOTO:
                            $objId = $contentInfo['photo']['photo_info']['id'];
                            $objType = BlockType::TYPE_PHOTO;
                            break;
                        case BlockType::TYPE_BLANK:
                            $objId = $contentInfo['blank']['blank_info']['bid'];
                            $objType = BlockType::TYPE_BLANK;
                            break;
                    }
                    $contentInfo['statSign'] = statSign::genStatSign(statSign::MODULE_BANGDAN_DETAIL_LIST, [
                        statSign::EXTEND_KEY_OBJ_ID => $objId,
                        statSign::EXTEND_KEY_OBJ_TYPE => $objType,
                        statSign::EXTEND_KEY_INDEX => $i,
                        statSign::EXTEND_KEY_POS => 'location_3',
                        statSign::EXTEND_KEY_RELATE_OBJ_ID => $ranking_id,
                        statSign::EXTEND_KEY_RELATE_OBJ_TYPE => BlockType::TYPE_RANKING,
                        statSign::EXTEND_KEY_URL_TYPE => $objType
                    ], [
                        'tab' => 'publicpraise'
                    ]);

                    $result[] = [
                        'wiki_info' => $wikiInfo,
                        'content_info' => [
                            'list' => $contentInfo,
                        ],
                    ];
                    $i++;
                }
            }
        }

        return $result;
    }

    public static function getContentInfo($obj_ids)
    {
        $content_info = [];
        $obj_ids = array_filter($obj_ids, function ($val) {
            return $val == '' ? false : true;
        });
        if ($obj_ids && is_array($obj_ids)) {
            $photoIds = [];
            $blankIds = [];
            foreach ($obj_ids as $obj_id) {
                $objType = IdParse::getType($obj_id);
                if ($objType == BlockType::TYPE_PHOTO) {
                    $photoIds[] = $obj_id;
                }
                if ($objType == BlockType::TYPE_ANSWER) {
                    $photoIds[] = $obj_id;
                }
                if ($objType == BlockType::TYPE_BLANK) {
                    $blankIds[] = $obj_id;
                }
            }
            $note_info = $photoIds ? HandleNote::handleNote($photoIds, HandleNote::BASE_INFO) : [];
            $blank_info = $blankIds ? HandleBlank::handleBlank($blankIds, HandleBlank::MASONRY_LAYOUTS) : [];
            foreach ($obj_ids as $obj_id) {
                if ($note_info[$obj_id]) {
                    $content_info[$obj_id] = $note_info[$obj_id];
                }
                if ($blank_info[$obj_id]) {
                    $content_info[$obj_id] = $blank_info[$obj_id];
                }
            }
        }

        return $content_info;
    }


    public static function getBrandByRankingId($ranking_id, $active_uid = 0, $limit = 20)
    {
        $rankingDay = self::getRankingDay();

        $list = WikiRankingBrand::getShowTop($ranking_id, $rankingDay, $limit);
        if (count($list) <= self::TOP_SHOW_CNT) {
            //    return [];
        }
        $brand_ids = array_column($list, 'brand_id');
        $brandUserInfos = Brand::getBrandUserInfos($brand_ids, true, false, true);

        $basic_ids = array_column($list, 'basic_id');
        $basic_info = $basic_ids ? sWiki::getWikiListByBasicIds($basic_ids, $active_uid) : [];
        $brandRankingCntMap = Ranking::getCountByBrandIdArr($brand_ids);//获取品牌榜数据
        $result = [];
        if ($list && is_array($list)) {
            $i = 0;
            foreach ($list as $val) {
                if ($val['basic_id'] && is_array($basic_info[$val['basic_id']]) && $val['brand_id'] && $brandUserInfos[$val['brand_id']]) {
                    $rankingCnt = $brandRankingCntMap[$val['brand_id']] ?? 0;
                    $statSign = statSign::genStatSign(statSign::MODULE_WIKI_RANKING_DETAIL_BRAND, [
                        statSign::EXTEND_KEY_OBJ_ID => $val['brand_id'],
                        statSign::EXTEND_KEY_INDEX => $i,
                    ], [
                        'uid' => $active_uid,
                        'basic_id' => $val['basic_id'],
                        'brand_id' => $val['brand_id'],
                        'ranking_id' => $ranking_id,
                    ]);
                    $wikiInfo = $basic_info[$val['basic_id']];
                    $wikiInfo['statSign'] = statSign::genStatSign(statSign::MODULE_BANGDAN_DETAIL_LIST, [
                        statSign::EXTEND_KEY_OBJ_ID => $basic_info[$val['basic_id']]['id'],
                        statSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI,
                        statSign::EXTEND_KEY_OBJ_UID => $basic_info[$val['basic_id']]['brand_id'],
                        statSign::EXTEND_KEY_INDEX => $i,
                        statSign::EXTEND_KEY_POS => 'location_5',
                        statSign::EXTEND_KEY_RELATE_OBJ_ID => $ranking_id,
                        statSign::EXTEND_KEY_RELATE_OBJ_TYPE => BlockType::TYPE_RANKING,
                        statSign::EXTEND_KEY_URL_TYPE => BlockType::TYPE_WIKI,
                    ], [
                        'tab' => 'brand'
                    ]);
                    if ($wikiInfo['brand_info']) {
                        $wikiInfo['brand_info']['statSign'] = statSign::genStatSign(statSign::MODULE_BANGDAN_DETAIL_LIST, [
                            statSign::EXTEND_KEY_OBJ_ID => $basic_info[$val['basic_id']]['id'],
                            statSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI,
                            statSign::EXTEND_KEY_OBJ_UID => $basic_info[$val['basic_id']]['brand_id'],
                            statSign::EXTEND_KEY_INDEX => $i,
                            statSign::EXTEND_KEY_POS => 'location_5',
                            statSign::EXTEND_KEY_RELATE_OBJ_ID => $ranking_id,
                            statSign::EXTEND_KEY_RELATE_OBJ_TYPE => BlockType::TYPE_RANKING,
                            statSign::EXTEND_KEY_URL_TYPE => BlockType::TYPE_BRAND,
                        ], [
                            'tab' => 'brand'
                        ]);
                    }
                    $result[] = [
                        'wiki_info' => $wikiInfo,
                        'brand' => $brandUserInfos[$val['brand_id']],
                        'ranking_info' => [
                            'desc' => "品牌共入选 " . $rankingCnt . " 个榜单",
                            'total_ranking' => $rankingCnt,
                        ],
                        'statSign' => $statSign,
                    ];
                    $i++;
                }
            }
        }

        return $result;
    }

    public static function getBrandInfo($brand_ids, $active_uid)
    {
        $brand_list = [];
        $uids = mBrand::getUidsByIds($brand_ids);

        $user_infos = sUser::getBrandCards($uids, $active_uid);
        if ($uids && is_array($uids)) {
            foreach ($uids as $brand_id => $uid) {
                $brand_list[$brand_id] = [
                    "user_info" => $user_infos[$uid],
                    "counter" => UserCounter::getOne($uid),
                ];
            }
        }
        return $brand_list;
    }

    /**
     * 根据品牌id集合获取对应的榜单数据集合
     * @param array $brandIdArr
     * @return array
     */
    public static function getCountByBrandIdArr(array $brandIdArr = []): array
    {
        if (empty($brandIdArr)) {
            return [];
        }
        $where = [
            'brand_id' => $brandIdArr,
            'ranking_day' => self::getRankingDay(),
            'ranking_state' => WikiRankingBrand::RANKING_STATE_SHOW,
            "GROUP" => "brand_id",
        ];
        $brandCount = WikiRankingBrand::getCountMaps($where);
        $brandCountRes = self::handleCount($brandCount);

        $hotCount = WikiRankingHot::getCountMaps($where);
        $hotCountRes = self::handleCount($hotCount);

        $userLikeCount = WikiRankingPublicPraise::getCountMaps($where);
        $userLikeCountRes = self::handleCount($userLikeCount);

        $res = [];
        foreach ($brandIdArr as $brandId) {
            $res[$brandId] = $brandCountRes[$brandId] + $hotCountRes[$brandId] + $userLikeCountRes[$brandId];
        }

        return $res;


    }

    public static function getWikiRankingForLego($rankingId, $uid)
    {
        $rankingInfo = WikiRankingConfig::getByWhere([
            'deep' => 2,
            'id' => $rankingId,
            'config_state' => WikiRankingConfig::CONFIG_STATE_SHOW,
        ], '*');
        $result = [];
        $hotList = self::getHotByRankingId($rankingId, $uid, 10);
        $hotList = array_slice($hotList, 0, 3);
        $publicPraiseList = self::getUserLikeByRankingId($rankingId, $uid, 10);
        $publicPraiseList = array_slice($publicPraiseList, 0, 3);
        $brandList = self::getBrandByRankingId($rankingId, $uid, 10);
        $brandList = array_slice($brandList, 0, 3);
        if ($hotList) {
            $rankingData = [
                'type' => Ranking::TYPE_HOT,
                'ranking_id' => $rankingId,
                'ranking_name' => $rankingInfo['ranking_name'],
                'background_color' => self::COLOR_ARRAY[random_int(0, 8)],
                'link' => Ranking::getRankingUrl($rankingId, Ranking::TYPE_HOT),
                'list' => []
            ];
            $i = 0;
            foreach ($hotList as $row) {
                $rankingData['list'][] = [
                    'top' => $i + 1,
                    'title' => $row['title'],
                    'cover_img' => $row['cover_img'],
                    'brand' => $row['brand_info'] ? [
                        'nick' => $row['brand_info']['nick'],
                        'avatar' => $row['brand_info']['avatar'],
                    ] : null,
                ];
                $i++;
            }
            $result[] = $rankingData;
        }
        if ($publicPraiseList) {
            $rankingData = [
                'type' => Ranking::TYPE_PUBLIC_PRAISE,
                'ranking_id' => $rankingId,
                'ranking_name' => $rankingInfo['ranking_name'],
                'background_color' => self::COLOR_ARRAY[random_int(0, 8)],
                'link' => Ranking::getRankingUrl($rankingId, Ranking::TYPE_PUBLIC_PRAISE),
                'list' => []
            ];
            $i = 0;
            foreach ($publicPraiseList as $row) {
                $wikiInfo = $row['wiki_info'];
                $rankingData['list'][] = [
                    'top' => $i + 1,
                    'title' => $wikiInfo['title'],
                    'cover_img' => $wikiInfo['cover_img'],
                    'brand' => $wikiInfo['brand_info'] ? [
                        'nick' => $wikiInfo['brand_info']['nick'],
                        'avatar' => $wikiInfo['brand_info']['avatar'],
                    ] : null,
                ];
                $i++;
            }
            $result[] = $rankingData;
        }
        if ($brandList) {
            $rankingData = [
                'type' => Ranking::TYPE_BRAND,
                'ranking_id' => $rankingId,
                'ranking_name' => $rankingInfo['ranking_name'],
                'background_color' => self::COLOR_ARRAY[random_int(0, 8)],
                'link' => Ranking::getRankingUrl($rankingId, Ranking::TYPE_BRAND),
                'list' => []
            ];
            $i = 0;
            foreach ($brandList as $row) {
                $brand = $row['brand'];
                $rankingData['list'][] = [
                    'top' => $i + 1,
                    'brand' => $brand,
                ];
                $i++;
            }
            $result[] = $rankingData;
        }
        return $result;
    }

    /**
     * @param $count
     * @return array
     */
    public static function handleCount($count): array
    {
        $res = [];
        foreach ($count as $item) {
            $res[$item['brand_id']] = $item['cnt'] ?? 0;
        }

        return $res;
    }

    /**
     * 查询wiki top排名最前的一个热度榜和一个口碑榜
     * @param $basicIds
     * @return array
     */
    public static function getWikiRanking($basicIds)
    {
        $day = self::getRankingDay();
        //取wiki basicId 中 排序靠前的一个榜单
        $hotRankingArr = cacheWikiRanking::getHotRankingByBasicIds($day, $basicIds);
        $publicPraiseRankingArr = cacheWikiRanking::getPublicPraiseRankingByBasicIds($day, $basicIds);

        $rankingIds = [];
        foreach ($hotRankingArr as $basicId => $row) {
            foreach ($row as $key => $val) {
                $rankingIds[] = $key;
            }
        }
        foreach ($publicPraiseRankingArr as $basicId => $row) {
            foreach ($row as $key => $val) {
                $rankingIds[] = $key;
            }
        }
        $rankingIds = array_unique($rankingIds);
        $rankingConfigList = [];
        if ($rankingIds) {
            $rankingConfigList = WikiRankingConfig::selectByWhere(['id' => $rankingIds], ['id', 'ranking_name']);
            $rankingConfigList = $rankingConfigList ? array_column($rankingConfigList, null, 'id') : [];
        }
        $result = [];
        foreach ($basicIds as $basicId) {
            $hot = $hotRankingArr[$basicId];
            $publicPraise = $publicPraiseRankingArr[$basicId];
//            $hotTopNum = 0;
//            $publicPraiseTopNum = 0;
            $basicTopArr = [];
            $rankData = [];

            if ($hot) {
                $rankingId = key($hot);
                $rankingName = isset($rankingConfigList[$rankingId]) ? $rankingConfigList[$rankingId]['ranking_name'] : '';
                $hotTopNum = $hot[$rankingId];
                $basicTopArr[$hotTopNum] = [
                    'type' => self::TYPE_HOT,
                    'ranking_id' => $rankingId,
                    'ranking_name' => $rankingName,
                    'top_num' => $hotTopNum,
                    'ranking_title' => $rankingName . '热度榜·TOP' . $hotTopNum,
                ];
                $rankData[] = $hotTopNum;
            }
            if ($publicPraise) {
                $rankingId = key($publicPraise);
                $rankingName = isset($rankingConfigList[$rankingId]) ? $rankingConfigList[$rankingId]['ranking_name'] : '';
                $publicPraiseTopNum = $publicPraise[$rankingId];
                $basicTopArr[$publicPraiseTopNum] = [
                    'type' => self::TYPE_PUBLIC_PRAISE,
                    'ranking_id' => $rankingId,
                    'ranking_name' => $rankingName,
                    'top_num' => $publicPraiseTopNum,
                    'ranking_title' => $rankingName . '口碑榜·TOP' . $publicPraiseTopNum,
                ];
                $rankData[] = $publicPraiseTopNum;
            }


            if ($basicTopArr && is_array($basicTopArr)) {
                ksort($basicTopArr);
                //  array_multisort($rankData, SORT_ASC, $basicTopArr);
                $result[$basicId] = array_values($basicTopArr);
            }
            //排名较高的靠前
//            if ($hotTopNum > 0 && $hotTopNum <= $publicPraiseTopNum) {
//                if ($basicTopArr[self::TYPE_HOT]) {
//                    $result[$basicId][] = $basicTopArr[self::TYPE_HOT];
//                }
//                if ($basicTopArr[self::TYPE_PUBLIC_PRAISE]) {
//                    $result[$basicId][] = $basicTopArr[self::TYPE_PUBLIC_PRAISE];
//                }
//            } else {
//                if ($basicTopArr[self::TYPE_PUBLIC_PRAISE]) {
//                    $result[$basicId][] = $basicTopArr[self::TYPE_PUBLIC_PRAISE];
//                }
//                if ($basicTopArr[self::TYPE_HOT]) {
//                    $result[$basicId][] = $basicTopArr[self::TYPE_HOT];
//                }
//            }
        }
        return $result;
    }

    /*展示品牌荣耀榜前2
     *
     * */
    public static function getBrandGlory($brand_id)
    {
        $link = Hhzurl::getDomain() . self::BRAND_URL . "?brand_id=" . $brand_id;
        //榜单改造
        $hotInfo = self::getBrandTop2($brand_id, new WikiRankingHot(), self::TYPE_HOT);
        $brandInfo = self::getBrandTop2($brand_id, new WikiRankingBrand(), self::TYPE_BRAND);
        $userLikeInfo = self::getBrandTop2($brand_id, new WikiRankingPublicPraise(), self::TYPE_PUBLIC_PRAISE);
        $ranking_list = array_merge($hotInfo['list'], $brandInfo['list'], $userLikeInfo['list']);

        $count = $hotInfo['count'] + $brandInfo['count'] + $userLikeInfo['count'];
        //榜单改造
        $result = [];
        if ($ranking_list && is_array($ranking_list) && $count > 0) {
            $result['desc'] = '共 ' . $count . ' 个榜单';
            $result['link'] = LinkFormat::encryptionLink($link);
            if ($ranking_list && is_array($ranking_list)) {
                self::sort($ranking_list, [
                    'top_num' => 'asc',
                    'rank_sort' => 'desc',
                ]);
            }
            $result['ranking_list'] = $ranking_list ?: [];
        }
        return $result;

    }

    /*获取荣耀榜top2数据
     *@param int brand_id
     * @param obj  obj 类
     * @return array return
     * */
    public static function getBrandTop2($brand_id, $obj, $type = '')
    {
        $link = Hhzurl::getDomain() . self::BRAND_URL . "?brand_id=" . $brand_id;
        $rankingDay = self::getRankingDay();
        $map = [
            'AND' => [
                'brand_id' => $brand_id,
                'ranking_day' => $rankingDay,
                'ranking_state' => WikiRankingHot::RANKING_STATE_SHOW,
            ],
            'ORDER' => ['top_num' => 'ASC'],
        ];
        $mapLimit = $map;
        $mapLimit['LIMIT'] = [0, 2];
        $list = $obj::getListByWhere($mapLimit);
        $ranking_list = [];
        if ($list && is_array($list)) {
            foreach ($list as $val) {
                switch ($type) {
                    case self::TYPE_HOT:
                        $desc = $val['ranking_name'] . '热度榜TOP' . $val['top_num'];
                        $rank_sort = 3;
                        break;
                    case self::TYPE_BRAND:
                        $desc = $val['ranking_name'] . '品牌榜TOP' . $val['top_num'];
                        $rank_sort = 1;
                        break;
                    case self::TYPE_PUBLIC_PRAISE:
                        $desc = $val['ranking_name'] . '口碑榜TOP' . $val['top_num'];
                        $rank_sort = 2;
                        break;
                    case self::TYPE_HOT_UP:
                        $desc = '热度飙升榜TOP' . $val['top_num'];
                        $rank_sort = self::TYPE_HOT_UP;
                        break;
                    case self::TYPE_PUBLIC_UP:
                        $rank_sort = self::TYPE_PUBLIC_UP;
                        $desc = '住友口碑榜TOP' . $val['top_num'];
                        break;
                }
                $ranking_list[] = [
                    'ranking_desc' => $desc,
                    'top_num' => (int)$val['top_num'],
                    'rank_sort' => $rank_sort,
                    'link' => LinkFormat::encryptionLink($link),
                ];
            }
        }
        $count = $obj::getCountMaps($map)[0]['cnt'] ?: 0;
        return ['list' => $ranking_list, 'count' => $count];
    }

    /**
     * 获取品牌 荣耀榜
     * @param int $brand_id
     *
     */
    public static function getBrandGroryByBrandId($brand_id)
    {
        $rankingDay = self::getRankingDay();
        $map = [
            'AND' => [
                'brand_id' => $brand_id,
                'ranking_day' => $rankingDay,
                'ranking_state' => WikiRankingBrand::RANKING_STATE_SHOW,
            ],
            'ORDER' => ['top_num' => 'ASC'],
        ];

        $brandList = WikiRankingBrand::getListByWhere($map);
        $hotList = WikiRankingHot::getListByWhere($map);
        $userlikeList = WikiRankingPublicPraise::getListByWhere($map);
        $result = [];
        if ($brandList && is_array($brandList)) {
            $rank_ids = [];
            foreach ($brandList as $val) {
                if (in_array($val['ranking_id'], $rank_ids)) {
                    continue;
                }
                $rank_ids[] = $val['ranking_id'];
                $continueinfo = WikiRankingBrandData::getByWhere([
                    'ranking_id' => $val['ranking_id'],
                    'data_type' => self::TYPE_BRAND,
                    'brand_id' => $brand_id,
                ]);
                $desc = '';
                if ($continueinfo && $continueinfo['continue_week'] >= 2) {
                    $desc = '连续' . $continueinfo['continue_week'] . "周上榜";
                }
                $result[$val['ranking_id']]['ranking_name'] = $val['ranking_name'];
                $result[$val['ranking_id']]['ranking_id'] = $val['ranking_id'];
                $result[$val['ranking_id']]['ranking_list'][] = [
                    'top_num' => $val['top_num'],
                    'desc' => $desc,
                    'type' => self::TYPE_BRAND,

                ];
                $result[$val['ranking_id']]['cnt'] += 1;
            }
        }
        if ($userlikeList && is_array($userlikeList)) {
            $rank_ids = [];
            foreach ($userlikeList as $val) {
                if (in_array($val['ranking_id'], $rank_ids)) {
                    continue;
                }
                $rank_ids[] = $val['ranking_id'];
                $continueinfo = WikiRankingBrandData::getByWhere([
                    'ranking_id' => $val['ranking_id'],
                    'data_type' => self::TYPE_PUBLIC_PRAISE,
                    'brand_id' => $brand_id,
                ]);
                $desc = '';
                if ($continueinfo && $continueinfo['continue_week'] >= 2) {
                    $desc = '连续' . $continueinfo['continue_week'] . "周上榜";
                }
                $result[$val['ranking_id']]['ranking_name'] = $val['ranking_name'];
                $result[$val['ranking_id']]['ranking_id'] = $val['ranking_id'];
                $result[$val['ranking_id']]['ranking_list'][] = [
                    'top_num' => $val['top_num'],
                    'desc' => $desc,
                    'type' => self::TYPE_PUBLIC_PRAISE,

                ];
                $result[$val['ranking_id']]['cnt'] += 1;
            }
        }
        if ($hotList && is_array($hotList)) {
            $rank_ids = [];
            foreach ($hotList as $val) {
                if (in_array($val['ranking_id'], $rank_ids)) {
                    continue;
                }
                $rank_ids[] = $val['ranking_id'];
                $continueinfo = WikiRankingBrandData::getByWhere([
                    'ranking_id' => $val['ranking_id'],
                    'data_type' => self::TYPE_HOT,
                    'brand_id' => $brand_id,
                ]);
                $desc = '';
                if ($continueinfo && $continueinfo['continue_week'] >= 2) {
                    $desc = '连续' . $continueinfo['continue_week'] . "周上榜";
                }
                $result[$val['ranking_id']]['ranking_name'] = $val['ranking_name'];
                $result[$val['ranking_id']]['ranking_id'] = $val['ranking_id'];
                $result[$val['ranking_id']]['ranking_list'][] = [
                    'top_num' => $val['top_num'],
                    'desc' => $desc,
                    'type' => self::TYPE_HOT,
                ];
                $result[$val['ranking_id']]['cnt'] += 1;
            }
        }
        //排序
        if ($result && is_array($result)) {
            $data_values = array();
            foreach ($result as &$info) {
                $data_values[] = $info['cnt'];
                if ($info['ranking_list'] && is_array($info['ranking_list'])) {
                    $rank_list = [];
                    $type_list = [];
                    foreach ($info['ranking_list'] as $rank) {
                        $rank_list[] = $rank['top_num'];
                        $type_list[] = $rank['type'];
                    }
                    array_multisort($rank_list, SORT_ASC, $type_list, SORT_DESC, $info['ranking_list']);
                }
            }
            array_multisort($data_values, SORT_DESC, $result);
        }
        //排序
        return array_values($result);
    }


    public static function multiFormatRankingCard($rankingIds, $num = 3)
    {
        $rankingList = self::getListByRankingIds($rankingIds, count($rankingIds));
        $list = [];
        foreach ($rankingList as $row) {
            $row['ranking_title'] = $row['ranking_name'] . "榜";
            $row['link'] = self::getRankingUrl($row['ranking_id'], self::TYPE_HOT);
            $list[$row['ranking_id']] = $row;
        }
        return $list;
    }

    public static function getRankingUrl($rankingId, $rankingType, $parentId = null)
    {
        $link = Hhzurl::getDomain() . '/brand/bangdan/detail?ranking_id=' . $rankingId . '&rank_type=' . $rankingType;
        if (!is_null($parentId)) {
            $link .= '&stair_id=' . $parentId;
        }
        return 'niceliving://webview/fullscreen?protego=' . urlencode(base64_encode(json_encode(['url' => $link])));
    }

    /**
     * 获取热榜推荐wiki列表
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function getTopHotWikiList($params): array
    {
        $current = $params['current_page'] * $params['per_page'];
        $offset = ($params['current_page'] - 1) * $params['per_page'];
        $rankingDay = self::getRankingDay();
        $where = [
            'ranking_id' => $params['ranking_id'],
            'ranking_state' => WikiRankingHot::RANKING_STATE_HIDE,
            'ranking_day' => $rankingDay,
            'top_num[<>]' => [10, 70],
            'ORDER' => ['top_num' => 'ASC', 'score' => 'DESC'],
        ];
        $total = WikiRankingHot::getCountByWhere($where);
        $data['total'] = $total ?: 0;
        $data['current_page'] = $params['current_page'];
        $data['per_page'] = $params['per_page'];
        $data['is_over'] = ($total <= $current) ? 1 : 0;
        $data['list'] = [];
        $where['LIMIT'] = [$offset, $params['per_page']];
        $basic_ids = WikiRankingHot::getListByWhere($where, 'basic_id') ?: [];
        $list = $basic_ids ? sWiki::getWikiListByBasicIds($basic_ids, $params['uid']) : [];
        $data['list'] = $list ? array_values($list) : [];

        return $data;
    }


    /**
     * 获取口碑榜推荐wiki列表
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function getTopPublicPraiseWikiList($params): array
    {
        $current = $params['current_page'] * $params['per_page'];
        $offset = ($params['current_page'] - 1) * $params['per_page'];
        $rankingDay = self::getRankingDay();
        $where = [
            'ranking_id' => $params['ranking_id'],
            'ranking_state' => WikiRankingPublicPraise::RANKING_STATE_HIDE,
            'ranking_day' => $rankingDay,
            'top_num[<>]' => [10, 70],
            'ORDER' => ['top_num' => 'ASC', 'score' => 'DESC'],
        ];
        $total = WikiRankingPublicPraise::getCountWhere($where);
        $data['total'] = $total ?: 0;
        $data['current_page'] = $params['current_page'];
        $data['per_page'] = $params['per_page'];
        $data['is_over'] = ($total <= $current) ? 1 : 0;
        $data['list'] = [];
        $where['LIMIT'] = [$offset, $params['per_page']];
        $basic_ids = WikiRankingPublicPraise::getListByWhere($where, 'basic_id') ?: [];
        $list = $basic_ids ? sWiki::getWikiListByBasicIds($basic_ids, $params['uid']) : [];
        $data['list'] = $list ? array_values($list) : [];

        return $data;
    }


    /**
     * 根据条件获取总数
     * @param $where
     * @return bool|int|mixed|string
     */
    public static function getTotal($where)
    {
        //查询总数
        $total = WikiRankingHot::getCountByWhere($where);

        return $total ?? 0;
    }

    /**
     * 获取推荐给用户的品牌榜单-搜索中间页
     * @return array 返回一个用户感兴趣的榜单分类对应的品牌列表
     */
    public static function getRecommendBrandRankingForSearch($uid)
    {
        $result = [
            'title' => '好物品牌榜',
            'brand_list' => []
        ];
        $realRankingIds = self::getRankingIdsByUserRealTime($uid);
        $realRankingId = ($realRankingIds && $realRankingIds[0]) ? $realRankingIds[0] : 0;

        $res = $realRankingId ? self::getBrandListByRankingIds($realRankingId, 10) : [];
        if ($res) {
            foreach ($res as $row) {
                if ($row['brand_count'] >= 10) {
                    $result['title'] = $row['ranking_name'] . '品牌榜';
                    $brandNames = [];
                    foreach ($row['ranking_list'] as $rankingRow) {
                        $brandNames[] = $rankingRow['brand_name'];
                    }
                    $result['brand_list'] = $brandNames;
                    break;
                }
            }
            if (!empty($result['brand_list'])) {
                self::realTimeBrand($uid, $realRankingId, $result['brand_list']);
            }
        }

        if (empty($result['brand_list'])) {
            $data = $uid ? UserRecommendWikiRanking::getRankingBrand($uid) : [];
            if (empty($data)) {
                self::createUserRecommendRankingBrand($uid);
                $data = $uid ? UserRecommendWikiRanking::getRankingBrand($uid) : [];
            }
            if ($data) {
                $result['title'] = $data['ranking_name'] . '品牌榜';
                $result['brand_list'] = $data['brand'];
            }
        }
        return ($result && $result['brand_list']) ? $result : [];
    }

    public static function realTimeBrand($uid, $realRankingId, $brandNames)
    {
        if ($uid && $realRankingId && !empty($brandNames)) {
            self::_async($uid, $realRankingId, $brandNames);
        }
    }

    public static function _async_realTimeBrand($uid, $realRankingId, $brandNames)
    {
        $expireTime = self::getCacheRankingExpire();
        UserRecommendWikiRanking::addRankingBrands($uid, $realRankingId, $brandNames, $expireTime, true);
    }

    /**
     * 首页推荐线-榜单模块使用
     * @param $uid
     * @param $rankingId
     * @return array
     */
    public static function getUserRecommendRanking($uid, $rankingId = 0)
    {
        $result = [];
        if (!$uid) {
            return $result;
        }
        if (empty($rankingId)) {
            $realRankingIds = self::getRankingIdsByUserRealTime($uid);
            $realRankingId = ($realRankingIds && $realRankingIds[0]) ? $realRankingIds[0] : 0;
            if ($realRankingId) {//实时推荐榜单
                $res = self::getListByRankingIds([$realRankingId], 3);
            } else {
                $rankingId = self::getCacheRankingId($uid);//查询缓存，如果没有，重新生成用户推荐的榜单数据
                if (empty($rankingId)) {
                    $res = self::createUserRecommendRanking($uid);
                    $expireTime = self::getCacheRankingExpire();
                    $resRankingIds = array_column($res, 'ranking_id');
                    UserRecommendWikiRanking::addRankingIds($uid, $resRankingIds, $expireTime);
                    self::getCacheRankingId($uid);
                } else {
                    $res = self::getListByRankingIds([$rankingId], 3);
                }
            }
        } else {
            $res = self::getListByRankingIds([$rankingId], 3);
        }
        if (empty($res)) {
            $rankingIds = [5];//兜底 餐桌榜
            $res = self::getListByRankingIds($rankingIds, 3);
        }
        $data = !empty($res) ? $res[0] : [];
        if ($data) {
            $rankingId = $data['ranking_id'];
            $userCount = $data['user_count'];
            if ($userCount > 10000) {
                $userCount = sprintf("%.1f", $userCount / 10000) . 'W';
            }
            $wikiList = $data['ranking_list'];
            $list = [];
            foreach ($wikiList as $item) {
                $list[] = [
                    'id' => $item['basic_id'],
                    'top_num' => $item['top'],
                    'cover_img' => $item['cover_img'],
                ];
            }
            $recommendation = WikiRankingConfig::getByWhere(['id' => $rankingId], 'recommendation');
            $recommendation = !empty($recommendation) ? $recommendation : '';
            $link = self::getRankingUrl($data['ranking_id'], self::TYPE_HOT);

            $rankingCoverData = Ranking::getHotRankingCover(Ranking::getRankingDay(), $rankingId);

            $coverImg = !empty($rankingCoverData) ? $rankingCoverData['cover_img'] : null;

            $result = [
                'type' => BlockType::TYPE_GOODS_RANKING,
                'title' => $data['ranking_name'] . '榜单',
                'subtitle' => '由 ' . $userCount . ' 位住友选出',
                'top_num' => $data['wiki_count'] ? 'TOP' . $data['wiki_count'] : '',
                "v6Title" => $data['ranking_name'] . 'TOP20',
                'recommendation' => $recommendation,
                'cover_pic_color' => '#000000',
                'ranking_id' => $data['ranking_id'],
                'list' => $list,
                'link' => $link,
                'cover_img' => $coverImg,
            ];
        }
        return $result;
    }

    private static function getCacheRankingId($uid)
    {
        if (!$uid) {
            return 0;
        }
        $rankingId = UserRecommendWikiRanking::getRankingId($uid);
        if ($rankingId) {
            $expire = self::getCacheRankingExpire();
            UserRecommendWikiRanking::addRankingId($uid, $rankingId, $expire);
        }
        return $rankingId;
    }

    private static function getCacheRankingExpire()
    {
        $rankingDay = self::getRankingDay();
        $nextDay = date('Ymd', strtotime('+1 days'));
        if ($rankingDay == $nextDay) {//如果明天是榜单上榜日期，则过期时间是明天0点
            $expireTime = strtotime($nextDay) - time();
        } else {
            $expireTime = strtotime(date('Y-m-d 08:00:00', strtotime('+1 days'))) - time();
        }
        return $expireTime;
    }

    private static function getMaxRankingExpireTime()
    {
        $rankingDay = self::getRankingDay();
        $nextRankingDay = date('Ymd', strtotime('+7 days', strtotime($rankingDay)));
        $time = time();
        $expireTime = strtotime($nextRankingDay) - $time - 1;
        $expireTime = $expireTime > 0 ? $expireTime : 0;
        return $expireTime;
    }

    public static function getHotRankingList()
    {
        $day = self::getRankingDay();
        $list = UserRecommendWikiRanking::getHotRanking($day);
        if (empty($list)) {
            $rankingIds = self::getHotRankingIds();
            $rankingIds = array_slice($rankingIds, 0, 20);
            $list = self::getListByRankingIds($rankingIds, 20);
            UserRecommendWikiRanking::addHotRanking($day, $list, 15 * 86400);
        }
        return $list;
    }

    private static function createUserRecommendRanking($uid)
    {
        $result = [];
        if (!$uid) {
            return $result;
        }

        $actionRankingIds = self::getRankingIdsByUserAction($uid);
        $rankingIds = $actionRankingIds;

        $actionList = $actionRankingIds ? self::getListByRankingIds($actionRankingIds) : [];
        $hotList = self::getHotRankingList();
        $list = [];
        foreach ($actionList as $row) {
            $rankingId = $row['ranking_id'];
            if (!isset($list[$rankingId])) {
                $list[$rankingId] = $row;
            }
        }
        foreach ($hotList as $row) {
            $rankingId = $row['ranking_id'];
            if (!isset($list[$rankingId])) {
                $list[$rankingId] = $row;
                $rankingIds[] = $rankingId;
            }
        }
        foreach ($rankingIds as $rankingId) {
            if (isset($list[$rankingId])) {
                $result[] = $list[$rankingId];
            }
        }
        return $result;
    }

    private static function createUserRecommendRankingBrand($uid)
    {
        if (!$uid) {
            return;
        }
        $actionRankingIds = self::getRankingIdsByUserAction($uid);

        $allRankingIds = WikiRankingConfig::selectByWhere([
            'deep' => 2,
            'config_state' => WikiRankingConfig::CONFIG_STATE_SHOW,
        ], 'id');

        $rankingIds = array_unique(array_merge($actionRankingIds, $allRankingIds));
        $res = $rankingIds ? self::getBrandListByRankingIds($rankingIds, 100) : [];
        $list = [];
        if ($res) {
            foreach ($res as $row) {
                if ($row['brand_count'] >= 10) {
                    $brandNames = [];
                    foreach ($row['ranking_list'] as $rankingRow) {
                        $brandNames[] = $rankingRow['brand_name'];
                    }
                    $brandNames = array_slice($brandNames, 0, 10);
                    $list[$row['ranking_id']] = ['brand' => $brandNames, 'ranking_name' => $row['ranking_name']];
                }
            }
        }
        $expireTime = self::getCacheRankingExpire();
        foreach ($rankingIds as $rankingId) {
            if (isset($list[$rankingId])) {
                UserRecommendWikiRanking::addRankingBrands($uid, $rankingId, $list[$rankingId], $expireTime);
            }
        }
    }

    public static function getRelateRankingIds($rankingIds)
    {
        $relateRankingArr = WikiRankingConfig::selectByWhere([
            'id' => $rankingIds,
            'config_state[!]' => WikiRankingConfig::CONFIG_STATE_DEL,
            'relate_id[!]' => '',
            'ORDER' => ['id' => $rankingIds]
        ], ['id', 'relate_id']);
        $relateRankingArr = $relateRankingArr ? array_column($relateRankingArr, null, 'id') : [];
        $relateIds = [];
        foreach ($relateRankingArr as $row) {
            $relateIdsArr = !empty($row['relate_id']) ? explode(',', $row['relate_id']) : [];
            $relateIds = array_merge($relateIds, $relateIdsArr);
        }
        $relateIds = array_diff($relateIds, $rankingIds);
        $relateIds = array_filter(array_unique($relateIds));
        return $relateIds;
    }

    /**
     * 获取推荐榜单-好物频道使用
     * @param $uid
     */
    public static function getRecommendRanking($uid)
    {
        if ($uid) {
            $realRankingIds = self::getRankingIdsByUserRealTime($uid);
            $realRankingId = ($realRankingIds && $realRankingIds[0]) ? $realRankingIds[0] : 0;
            $rankingIds = $realRankingId ? [$realRankingId] : [];
            $actionRankingIds = self::getRankingIdsByUserAction($uid);
            $rankingIds = array_merge($rankingIds, $actionRankingIds);
            $rankingIds = array_unique($rankingIds);
        } else {
            $rankingIds = self::getHotRankingIds();
            $rankingIds = array_slice($rankingIds, 0, 5);
        }

        $res = $rankingIds ? self::getListByRankingIds($rankingIds, 5) : [];
        $count = count($res);
        if ($res && $count < 5) {//不足5个，查询关联的榜单补位
            $selectRankingIds = array_column($res, 'ranking_id');
            $relateIds = self::getRelateRankingIds($selectRankingIds);
            $relateRes = $relateIds ? self::getListByRankingIds($relateIds, 5 - $count) : [];
            $res = array_merge($res, $relateRes);
            $rankingIds = array_merge($rankingIds, $relateIds);
        }
        $list = [];
        if (!empty($res)) {
            $rankings = [];
            foreach ($res as $row) {
                $rankings[$row['ranking_id']] = $row;
            }
            foreach ($rankingIds as $rankingId) {
                if (isset($rankings[$rankingId])) {
                    $list[] = $rankings[$rankingId];
                }
            }
        } else {
            $list = self::getHotRankingList();
            $list = array_slice($list, 0, 5);
            shuffle($list);
        }
        return $list;
    }

    /**
     * 根据用户行为查询推荐的榜单
     * @param $uid
     * @return array
     */
    public static function getRankingIdsByUserAction($uid)
    {
        if (!$uid) {
            return [];
        }
        $result = UserRecommendWikiRanking::getUserActionCate($uid);
        if (empty($result)) {
            $cache = $uid ? UserPortraitApi::requestFromBrand($uid, ['recommend_brand_cate_30d']) : [];
            $cateIdsStr = ($cache && isset($cache['recommend_brand_cate_30d'])) ? $cache['recommend_brand_cate_30d'] : '';
            $cateIds = $cateIdsStr ? explode(',', $cateIdsStr) : [];
            $result = $cateIds ? self::getRankingIdsByCateIds($cateIds) : [];
            UserRecommendWikiRanking::addUserActionCate($uid, $result);
        }
        return $result;
    }

    /**
     * 查询用户实时推荐的榜单
     * @param $uid
     * @param $num 返回的榜单数量
     * @return array
     */
    public static function getRankingIdsByUserRealTime($uid, $num = 1)
    {
        if (!$uid) {
            return [];
        }
        $cateIdsStr = UserRealTimeCategory::getCategory($uid);
        $cateIds = $cateIdsStr ? explode(',', $cateIdsStr) : [];
        $result = $cateIds ? self::getRankingIdsByCateIds($cateIds) : [];
        Log::info($uid . '# get real time ranking', $result);
        self::realTime($uid, $result);
        return $result ? array_slice($result, 0, $num) : [];
    }

    public static function realTime($uid, $realRankingIds)
    {
        if ($uid && $realRankingIds) {
            self::_async($uid, $realRankingIds);
        }
    }

    public static function _async_realTime($uid, $realRankingIds)
    {
        if ($uid && $realRankingIds) {
            UserRealTimeCategory::delCategory($uid);
            $res = self::getListByRankingIds($realRankingIds, 3);
            if (!empty($res)) {
                $expireTime = self::getCacheRankingExpire();
                UserRecommendWikiRanking::addRankingIds($uid, $realRankingIds, $expireTime, true);
            }
        }
    }


    public static function getBasicPicHash($rankingList)
    {
        $basicPicHash = [];
        if ($rankingList && is_array($rankingList)) {
            foreach ($rankingList as $val) {
                if ($val['basic_pic_id']) {
                    $basicPicHash[$val['basic_id']] = $val['basic_pic_id'];;
                }
            }
        }
        return $basicPicHash;
    }

    //处理榜单wiki的封面图片
    public static function HandleBasicPic($basic_info, $baiscPicHash)
    {

        if ($basic_info && is_array($basic_info)) {
            foreach ($basic_info as $basicId => &$val) {
                //img
                if ($baiscPicHash[$basicId]) {
                    $cover_img = $baiscPicHash[$basicId] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $baiscPicHash[$basicId],
                        ImgUrl::IMAGE_SIZE_OP_ORI) : '';
                } else {
                    $cover_img = isset($val['cover_img']) ? $val['cover_img'] : '';
                }
                //img
                $val['cover_img'] = $cover_img ?: '';
            }
        }
        return $basic_info;
    }


    private static function getRankingIdsByCateIds($cateIds)
    {
        $result = [];
        $list = $cateIds ? WikiRankingCategory::selectByWhere([
            'cate_id' => $cateIds,
            'cate_state' => WikiRankingCategory::CAT_STATE_NORMAL
        ], ['ranking_id', 'cate_id']) : [];
        $rankingIdsArr = [];
        foreach ($list as $row) {
            foreach ($cateIds as $key => $cateId) {
                if ($row['cate_id'] == $cateId) {
                    if (!isset($rankingIdsArr[$row['ranking_id']]) || $rankingIdsArr[$row['ranking_id']]['key'] <= $key) {
                        $rankingIdsArr[$row['ranking_id']] = ['key' => $key, 'cate_id' => $cateId];
                    }
                }
            }
        }
        $rankingIds = [];
        foreach ($rankingIdsArr as $rankingId => $row) {
            $rankingIds[$row['key']] = $rankingId;
        }
        if ($rankingIds) {
            ksort($rankingIds);
            $result = array_values($rankingIds);
        }
        return array_unique(array_filter($result));
    }


    /*sort 方法
     *
     *
     * */
    public static function sort(array &$rows, array $sorts)
    {

        $args = [];
        foreach ($sorts as $field => $direction) {
            $col = array_column($rows, $field);
            $args[] = $col;
            if ('asc' === $direction) {
                $args[] = SORT_ASC;
            } else {
                $args[] = SORT_DESC;
            }
        }
        $args[] = &$rows;
        call_user_func_array("array_multisort", $args);
    }

    public static function setHotRankingCover($id)
    {
        $wikiHotRankingInfo = WikiRankingHot::get('*', ['id' => $id]);

        if ($wikiHotRankingInfo && is_array($wikiHotRankingInfo)) {

            if (!empty($wikiHotRankingInfo['basic_pic_id'])) {
                $coverImg = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $wikiHotRankingInfo['basic_pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI);
            } else {
                $wikiBasicInfos = WikiBasic::getWikiBasicInfoByIds([$wikiHotRankingInfo['basic_id']]);
                $coverImg = $wikiBasicInfos[$wikiHotRankingInfo['basic_id']]['cover_img'];
            }

            if (empty($coverImg)) {
                return false;
            }

            cacheWikiRanking::setHotRankingCover(
                $wikiHotRankingInfo['ranking_day'],
                $wikiHotRankingInfo['ranking_id'],
                $id,
                $coverImg
            );

            return true;
        }

        return false;
    }

    public static function getHotRankingCover($rankingDay, $rankingId)
    {
        $data = cacheWikiRanking::getHotRankingCover($rankingDay, $rankingId);
        return $data;
    }

    public static function delHotRankingCover($rankingDay, $rankingId)
    {
        cacheWikiRanking::delHotRankingCover($rankingDay, $rankingId);
        return true;
    }

    /**
     * 获取默认热门榜单id
     * @return int|mixed|string|null
     */
    public static function getDefaultRankingId()
    {
        $hotTopRankingIds = self::getHotRankingIds();
        $rankingId = $hotTopRankingIds ? $hotTopRankingIds[0] : null;
        return $rankingId;
    }

    /**
     * 获取热门榜单ids
     * @return array|int[]|string[]
     */
    public static function getHotRankingIds()
    {
        $day = self::getRankingDay();
        $rankingDataList = cacheWikiRanking::getWikiRankingDataIds($day);
        $rankingIds = $rankingDataList ? array_keys($rankingDataList) : [];

        $hotRankingIds = self::getAllShowRankingIds(self::TYPE_HOT);
        $hotTopRankingIds = array_intersect($rankingIds, $hotRankingIds);
        return $hotTopRankingIds ? $hotTopRankingIds : $hotRankingIds;
    }

    /**
     * 获取所有分类列表
     * @return array
     */
    public static function getAllRankingCategoryList()
    {
        $hotTopPageSize = 20;
        $result = [];

        $day = self::getRankingDay();
        $rankingDataList = cacheWikiRanking::getWikiRankingDataIds($day);
        $rankingIds = $rankingDataList ? array_keys($rankingDataList) : [];

        $hotRankingIds = self::getAllShowRankingIds(self::TYPE_HOT);
        $hotTopRankingIds = array_intersect($rankingIds, $hotRankingIds);
        $hotTopRankingIds = array_slice($hotTopRankingIds, 0, $hotTopPageSize);

        $pubRankingIds = self::getAllShowRankingIds(self::TYPE_PUBLIC_PRAISE);
        $pubTopRankingIds = array_intersect($rankingIds, $pubRankingIds);
        $pubTopRankingIds = array_slice($pubTopRankingIds, 0, $hotTopPageSize);

        $brandRankingIds = self::getAllShowRankingIds(self::TYPE_BRAND);
        $brandTopRankingIds = array_intersect($rankingIds, $brandRankingIds);
        $brandTopRankingIds = array_slice($brandTopRankingIds, 0, $hotTopPageSize);

        $allRankings = WikiRankingConfig::selectByWhere(['deep' => [1, 2], 'config_state' => WikiRankingConfig::CONFIG_STATE_SHOW, 'ORDER' => ['sort' => 'ASC', 'id' => 'ASC']], ['id', 'ranking_name', 'pid', 'sort']);
        $allRankings = array_column($allRankings, null, 'id');
        $firstRankings = [];
        $parentRankings = [];
        foreach ($allRankings as $row) {
            if ($row['pid'] == 0) {
                $firstRankings[$row['id']] = $row;
            } else if ($row['pid'] > 0) {
                $parentRankings[$row['pid']][] = $row;
            }
        }

        $result[self::TYPE_HOT][0] = [
            'first_ranking_name' => '热门',
            'id' => 0,
            'second_ranking_list' => []
        ];
        $result[self::TYPE_PUBLIC_PRAISE][0] = [
            'first_ranking_name' => '热门',
            'id' => 0,
            'second_ranking_list' => []
        ];
        $result[self::TYPE_BRAND][0] = [
            'first_ranking_name' => '热门',
            'id' => 0,
            'second_ranking_list' => []
        ];
        foreach ($hotTopRankingIds as $topRankingId) {
            if (isset($allRankings[$topRankingId]) && $allRankings[$topRankingId]) {
                $result[self::TYPE_HOT][0]['second_ranking_list'][] = [
                    'ranking_id' => (int)$topRankingId,
                    'ranking_name' => $allRankings[$topRankingId]['ranking_name']
                ];
            }
        }
        foreach ($pubTopRankingIds as $topRankingId) {
            if (isset($allRankings[$topRankingId]) && $allRankings[$topRankingId]) {
                $result[self::TYPE_PUBLIC_PRAISE][0]['second_ranking_list'][] = [
                    'ranking_id' => (int)$topRankingId,
                    'ranking_name' => $allRankings[$topRankingId]['ranking_name']
                ];
            }
        }
        foreach ($brandTopRankingIds as $topRankingId) {
            if (isset($allRankings[$topRankingId]) && $allRankings[$topRankingId]) {
                $result[self::TYPE_BRAND][0]['second_ranking_list'][] = [
                    'ranking_id' => (int)$topRankingId,
                    'ranking_name' => $allRankings[$topRankingId]['ranking_name']
                ];
            }
        }

        foreach ($firstRankings as $row) {
            $firstId = $row['id'];
            $result[self::TYPE_HOT][$firstId] = [
                'first_ranking_name' => $row['ranking_name'],
                'id' => (int)$firstId,
                'second_ranking_list' => []
            ];
            $result[self::TYPE_PUBLIC_PRAISE][$firstId] = [
                'first_ranking_name' => $row['ranking_name'],
                'id' => (int)$firstId,
                'second_ranking_list' => []
            ];
            $result[self::TYPE_BRAND][$firstId] = [
                'first_ranking_name' => $row['ranking_name'],
                'id' => (int)$firstId,
                'second_ranking_list' => []
            ];
            $secondRankingList = $parentRankings[$firstId] ?? [];
            foreach ($secondRankingList as $secondRow) {
                $secondRankingId = $secondRow['id'];
                if (in_array($secondRankingId, $hotRankingIds)) {
                    $result[self::TYPE_HOT][$firstId]['second_ranking_list'][] = [
                        'ranking_id' => (int)$secondRankingId,
                        'ranking_name' => $secondRow['ranking_name']
                    ];
                }
                if (in_array($secondRankingId, $pubRankingIds)) {
                    $result[self::TYPE_PUBLIC_PRAISE][$firstId]['second_ranking_list'][] = [
                        'ranking_id' => (int)$secondRankingId,
                        'ranking_name' => $secondRow['ranking_name']
                    ];
                }
                if (in_array($secondRankingId, $brandRankingIds)) {
                    $result[self::TYPE_BRAND][$firstId]['second_ranking_list'][] = [
                        'ranking_id' => (int)$secondRankingId,
                        'ranking_name' => $secondRow['ranking_name']
                    ];
                }
            }
        }
        return $result;
    }

    /**
     * 获取上榜的榜单id
     * @param $type
     * @return array
     */
    public static function getAllShowRankingIds($type = self::TYPE_HOT)
    {
        $rankingDay = self::getRankingDay();
        $rankingIds = cacheWikiRanking::getShowRankingIds($rankingDay, $type);
        return $rankingIds;
    }

    /**
     * 设置上榜的榜单id缓存
     * @return void
     */
    public static function setShowRankingIds()
    {
        $rankingDay = self::getRankingDay();
        $hotRankingIds = WikiRankingHot::getShowRankingIds($rankingDay);
        $pubRankingIds = WikiRankingPublicPraise::getShowRankingIds($rankingDay);
        $brandRankingIds = WikiRankingBrand::getShowRankingIds($rankingDay);
        cacheWikiRanking::setShowRankingIds($rankingDay, self::TYPE_HOT, $hotRankingIds);
        cacheWikiRanking::setShowRankingIds($rankingDay, self::TYPE_PUBLIC_PRAISE, $pubRankingIds);
        cacheWikiRanking::setShowRankingIds($rankingDay, self::TYPE_BRAND, $brandRankingIds);
    }

    /**
     * 获取创建榜单的日期
     * @return array
     */
    public static function getCreateRankingDay()
    {
        $time = time();
        $week = date('w', $time);
        $week = ($week == 0) ? 7 : $week;
        $day = date("Ymd", (self::CONST_RANKING_WEEK_DAY - $week) * 86400 + $time);//本周三日期
        $sourceDay = date("Ymd", strtotime($day) - 2 * 86400);

        return ['day' => $day, 'source_day' => $sourceDay];
    }

    /**
     * 获取榜单日期
     * @return string
     */
    public static function getRankingDay()
    {
        $rankDay = '';
        $time = time();
        $day = date('Ymd');
        $week = date('w', $time);
        $week = ($week == 0) ? 7 : $week;
        $currentWeekDay = date("Ymd", (self::CONST_RANKING_WEEK_DAY - $week) * 86400 + $time);//本周三日期
        $lastWeekDay = date('Ymd', strtotime('-7 days', strtotime($currentWeekDay)));
        $nextWeekDay = date('Ymd', strtotime('+7 days', strtotime($currentWeekDay)));
        if ($day >= $lastWeekDay && $day < $currentWeekDay) {
            $rankDay = $lastWeekDay;
        } else {
            if ($day >= $currentWeekDay && $day < $nextWeekDay) {
                $rankDay = $currentWeekDay;
            }
        }
        return $rankDay;
    }

    /**
     * redis迁移
     * 获取缓存数据
     */
    public static function getCacheData($rankingId)
    {
        $newRedis = new newCache(redisKeys::KEY_B_CACHE_WEEKLY_RANKING_COLO_FINE_GOODS);
        $data = $newRedis->getCache($rankingId);
        if (!$data) {
            self::setCacheData($rankingId);
            $data = $newRedis->getCache($rankingId);
        }
        return $data;
    }

    public static function setCacheData($rankingId)
    {
        $redis = new newCache(redisKeys::KEY_B_CACHE_WEEKLY_RANKING_COLO_FINE_GOODS);
        $sColor = self::COLOR_ARRAY[random_int(0, 8)];
        $redis->setCache($sColor, $rankingId);
    }

    public const COLOR_ARRAY = [
        '#B59394',
        '#A28273',
        '#B09771',
        '#9DAA7E',
        '#77A5A4',
        '#7995AE',
        '#8C9CAB',
        '#958EA6',
        '#8F788B',
    ];


}
